<?php
class Admin_PtrtinraoController extends Zendhlt_Controller_AdminAction {

	const ACTIVE = 0;
	
	//Mang tham so nhan duoc o moi Action
	protected $_arrParam;

	//Duong dan cua Controller
	protected $_currentController;

	//Duong dan cua Action chinh
	protected $_actionMain;

	//Admin user dang login
	protected $_crrUsra;
	//Thong so phan trang
	protected $_paginator = array('itemCountPerPage' => 10, 'pageRange' => 5);
	protected $_namespace;

	public function init() {
		$this->view->addHelperPath("ZendX/JQuery/View/Helper", "ZendX_JQuery_View_Helper");
		$layoutPath = TEMPLATE_PATH  . '/admin';
		$option = array ('layout' => 'index',
                   'layoutPath' => $layoutPath );
		Zend_Layout::startMvc ( $option );

		//Mang tham so nhan duoc o moi Action
		$this->_arrParam = $this->_request->getParams();

		//Duong dan cua Controller
		$this->_currentController = '/' . $this->_arrParam['module']
		. '/' . $this->_arrParam['controller'];

		//Duong dan cua Action chinh
		$this->_actionMain = '/' . $this->_arrParam['module']
		. '/' . $this->_arrParam['controller'];

		$this->_paginator['currentPage'] = $this->_request->getParam('page', 1);
		$this->_arrParam['paginator'] = $this->_paginator;

		//Luu cac du lieu filter vao SESSION
		//Dat ten SESSION
		$this->_namespace = $this->_arrParam['module'] . '-' . $this->_arrParam['controller'];
		$ssFilter = new Zend_Session_Namespace($this->_namespace);
		//$ssFilter->unsetAll();

		if(empty($ssFilter->col)){
			$ssFilter->keywords 	= '';
			$ssFilter->col 			= 'id';
			$ssFilter->order 		= 'DESC';
			$ssFilter->state 		= self::ACTIVE;
			$ssFilter->filter_col   = 'trang_thai';
			$ssFilter->filter_val   = '';
		}
		$this->_arrParam['ssFilter']['keywords']  = $ssFilter->keywords;
		$this->_arrParam['ssFilter']['col'] 	  = $ssFilter->col;
		$this->_arrParam['ssFilter']['order'] 	  = $ssFilter->order;
		$this->_arrParam['ssFilter']['state'] 	  = $ssFilter->state;
		$this->_arrParam['ssFilter']['filter_col']= $ssFilter->filter_col;
		$this->_arrParam['ssFilter']['filter_val']= $ssFilter->filter_val;

		//Truyen ra view
		$this->view->arrParam = $this->_arrParam;
		$this->view->currentController = $this->_currentController;
		$this->view->actionMain = $this->_actionMain;
		//Lay thong tin admin user hien tai
		$auth = Zend_Auth::getInstance();
		$this->_crrUsra = $auth->getIdentity();
	}

	public function indexAction() {
		// Title
		$this->view->headTitle('Danh sách Tin rao phòng trọ');
		$model = new Admin_Model_PtrTinRaoMapper();
		$items = $model->fetch($this->_arrParam,$id = 0,$curruser=$this->_crrUsra->id,$option ='view');
		$totalItem = $model->countItem($this->_arrParam,$id = 0,$curruser=$this->_crrUsra->id,$option ='view');
		$paginator = new Zendhlt_Paginator();
		$this->view->panigator = $paginator->createPaginator($totalItem, $this->_paginator);
		$this->view->totalItems = $totalItem;
		$this->view->Items = $items;
	}

	public function filterAction() {
		$ssFilter = new Zend_Session_Namespace($this->_namespace);

		if($this->_arrParam['type'] == 'search') {
			if($this->_arrParam['key'] == 1){
				$ssFilter->keywords = trim($this->_arrParam['keywords']);
			} else {
				$ssFilter->keywords = '';
				$ssFilter->filter_col   = '';
				$ssFilter->filter_val   = '';
			}
		}
		if($this->_arrParam['type'] == 'state') {
			$ssFilter->state = $this->_arrParam['state'];
		}
		if($this->_arrParam['type'] == 'filter') {
			$ssFilter->filter_col = $this->_arrParam['filter_col'];
			$ssFilter->filter_val = $this->_arrParam['filter_val'];
		}
		if($this->_arrParam['type'] == 'order') {
			$ssFilter->col = $this->_arrParam['col'];
			$ssFilter->order = $this->_arrParam['by'];
		}
		$this->_redirect($this->_actionMain);
		$this->_helper->viewRenderer->setNoRender();
	}
	
	public function changestatusAction() {
		//get pram from view
		$mapper = new Admin_Model_PtrTinRaoMapper();
		$id = $this->_arrParam['id'];
		$newstatus = $this->_arrParam['newsts'];
		$items = $mapper->fetchWithQuery('id='.$id);
		
		if ($items[0]!=NULL) {
			$item = new Admin_Model_TableColumn_PtrTinRao();
			$item=$items[0];
			$oldstatus=$item->getTrang_thai();
			$item->setId($id);
			$item->setTrang_thai($newstatus);
			$item->setNguoi_duyet($this->_crrUsra->id);
			$stsArr = array('0'=>"Chưa duyệt",'1'=>"Đã duyệt",'2'=>"Yêu cầu thay đổi",'3'=>"Không hợp lệ");
			//change status
			if($mapper->save($item,$task = 'changestatus')){
				//send message
				$msgoption =  array('id'		    =>0,
									'nguoi_nhan'    =>$item->getNguoi_dang(),
									'nguoi_gui'     =>$this->_crrUsra->id,
									'ngay_gui' 	    =>date('Y-m-d H:i:s'),
									'tieu_de' 	    =>'Cập nhật trạng thái tin rao',
									'noi_dung'	    =>'Tin rao có mã số '.$item->getId().' đã được cập nhật trạng thái như sau:\n 
														Trạng thái cũ: '.$stsArr[$oldstatus].' Trạng thái mới '.$stsArr[$newstatus],
									'loai'		    =>3,//Loại msg3: admin -> user
									'ptr_tin_rao'	=>$item->getId(),
									);
				$msg = new Admin_Model_TableColumn_TinNhan($msgoption );
				$msgMapper  = new Admin_Model_TinNhanMapper();
				$msgMapper->save($msg);
				//send email
				$transport = Zend_Registry::get('mailTransport');
				$defaultFrom = Zend_Registry::get('defaultFrom');
				$defaultReplyTo = Zend_Registry::get('defaultReplyTo');
				$email_from = $defaultFrom['email'];
				$name_from = $defaultFrom['name'];
				$email_to = $item->getNguoiDangObj()->email;
				$name_to = $item->getNguoiDangObj()->ho_ten;
				
				
				$m = new Zendhlt_Mail_Mail();
				$m->setSubject("[Kênh nhà trọ] Thay đổi trạng thái tin rao")
				  ->addTo($email_to)
				  ->setViewParam('id',$id)
				  ->setViewParam('username',$item->getNguoiDangObj()->ho_ten)
				  ->setViewParam('fromsts',$stsArr[$oldstatus])
				  ->setViewParam('tosts',$stsArr[$newstatus])
				  ->sendHtmlTemplate("changestatus.tpl","UTF-8",$transport);
			}
		}
		$this->_redirect($this->_actionMain);
		$this->_helper->viewRenderer->setNoRender();
	}
	
	public function sendmsgAction() {
		//get pram from view
		$mapper = new Admin_Model_PtrTinRaoMapper();
		$id = $this->_arrParam['id'];
		$items = $mapper->fetchWithQuery('id='.$id);
		$title = $this->_arrParam['id'];
		echo $title;
		if ($items[0]!=NULL) {
			$item = new Admin_Model_TableColumn_PtrTinRao();
			$item=$items[0];
			$oldstatus=$item->getTrang_thai();
			$item->setId($id);
			$item->setTrang_thai($newstatus);
			$item->setNguoi_duyet($this->_crrUsra->id);
			$stsArr = array('0'=>"Chưa duyệt",'1'=>"Đã duyệt",'2'=>"Yêu cầu thay đổi",'3'=>"Không hợp lệ");
			//change status
			if($mapper->save($item,$task = 'changestatus')){
				//send message
				$msgoption =  array('id'		    =>0,
									'nguoi_nhan'    =>$item->getNguoi_dang(),
									'nguoi_gui'     =>$this->_crrUsra->id,
									'ngay_gui' 	    =>date('Y-m-d H:i:s'),
									'tieu_de' 	    =>$title,
									'noi_dung'	    =>'Tin rao có mã số '.$item->getId().' đã được cập nhật trạng thái như sau:\n 
														Trạng thái cũ: '.$stsArr[$oldstatus].' Trạng thái mới '.$stsArr[$newstatus],
									'loai'		    =>3,//Loại msg3: admin -> user
									'ptr_tin_rao'	=>$item->getId(),
									);
				$msg = new Admin_Model_TableColumn_TinNhan($msgoption );
				$msgMapper  = new Admin_Model_TinNhanMapper();
				$msgMapper->save($msg);
			
			}
		}
		$this->_redirect($this->_actionMain);
		$this->_helper->viewRenderer->setNoRender();
		print($this->_arrParam);
	}
	
	public function deleteAction() {
		if (isset($this->_arrParam['cid'])) {
			$id = implode(',', $this->_arrParam['cid']);
		} else {
			$id = $this->_arrParam['id'];
		}

		$model = new Admin_Model_PtrTinRaoMapper();
		if (isset($this->_arrParam['rm'])) {
			$model->delete($id);
			$model = new Admin_Model_TinNhanMapper();
			$model->delete($id, 'ptr_tin_rao');
		} else {
			$data = array('trang_thai' => 4);
			$model->change($id, $data);
		}

		$this->_redirect('/admin/ptrtinrao');
	}
}